﻿using KeyboardBubble.Common;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Reflection.Emit;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.ProgressBar;

namespace KeyboardBubble
{
    public partial class Main : Form
    {
        private StringBuilder logs = new StringBuilder();
        public HotkeyManager hotkeyManager = new HotkeyManager();
        private static bool exactMode = true;

        private static Main mainWin;

        public static Main Instance
        {
            get
            {
                if (mainWin == null || mainWin.IsDisposed)
                {
                    mainWin = new Main();
                }
                return mainWin;
            }
        }

        public Main()
        {
            InitializeComponent();

            _hookID = SetHook(_proc);
            // 注册快捷键
            hotkeyManager.RegisterHotkey("visualstudio");
        }

        private const int WH_KEYBOARD_LL = 13;
        private const int WM_KEYDOWN = 0x0100;
        private const int WM_KEYUP = 0x0101;
        private static LowLevelKeyboardProc _proc = HookCallback;
        private static IntPtr _hookID = IntPtr.Zero;

        private static IntPtr SetHook(LowLevelKeyboardProc proc)
        {
            using (Process curProcess = Process.GetCurrentProcess())
            using (ProcessModule curModule = curProcess.MainModule)
            {
                return SetWindowsHookEx(WH_KEYBOARD_LL, proc,
                    GetModuleHandle(curModule.ModuleName), 0);
            }
        }

        private delegate IntPtr LowLevelKeyboardProc(
            int nCode, IntPtr wParam, IntPtr lParam);

        [DllImport("user32.dll")]
        private static extern int MapVirtualKey(uint uCode, int uMapType);

        private static HashSet<int> pressedKeys = new HashSet<int>();
        private static IntPtr HookCallback(
            int nCode, IntPtr wParam, IntPtr lParam)
        {
            if (nCode >= 0)
            {
                int vkCode = Marshal.ReadInt32(lParam);
                string code = ((Keys)vkCode).ToString();
                if (wParam == (IntPtr)WM_KEYDOWN)
                {
                    pressedKeys.Add(vkCode);
                }
                else if (wParam == (IntPtr)WM_KEYUP)
                {
                    // 检查当前按下的键是否与快捷键匹配
                    bool isShow= Main.Instance.hotkeyManager.CheckHotkeys(pressedKeys);
                    // 快捷键列表不存在，并且精确模式下，打印所有按键
                    if (!isShow && exactMode)
                    {
                        WinManager.Instance.AddWin(code);
                    }
                    pressedKeys.Remove(vkCode);
                }
            }
            return CallNextHookEx(_hookID, nCode, wParam, lParam);
        }

        [DllImport("user32.dll")]
        private static extern short GetAsyncKeyState(Keys vKey);
        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern IntPtr SetWindowsHookEx(int idHook,
            LowLevelKeyboardProc lpfn, IntPtr hMod, uint dwThreadId);

        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool UnhookWindowsHookEx(IntPtr hhk);

        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode,
            IntPtr wParam, IntPtr lParam);

        [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern IntPtr GetModuleHandle(string lpModuleName);

        private void Main_FormClosed(object sender, FormClosedEventArgs e)
        {
            UnhookWindowsHookEx(_hookID);
        }
    }
}
